﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace hxy.CopyRight
{
	/// <summary>
	/// 注册码的生成器和解析器。
	/// </summary>
	public class RegisterCodeManager
	{
		private static readonly string PWD = "hxy";

		/// <summary>
		/// 把两个时间封装进来，并返回加密后了字符串。
		/// </summary>
		/// <param name="useTimeLimit"></param>
		/// <param name="registerTimeLimit"></param>
		/// <returns></returns>
		public static string EncryptCode(DateTime useTimeLimit, DateTime registerTimeLimit)
		{
			//18位
			var strUseTime = useTimeLimit.Ticks.ToString();
			if (strUseTime.Length != 18) throw new InvalidOperationException("strUseTime.Length != 18 must be false.");

			var strRegisterTime = registerTimeLimit.Ticks.ToString();
			if (strRegisterTime.Length != 18) throw new InvalidOperationException("strRegisterTime.Length != 18 must be false.");

			//把两个序列简单地分解为四组，再重新组合
			var u1 = strUseTime.Substring(0, 9);
			var u2 = strUseTime.Substring(9, 9);
			var r1 = strRegisterTime.Substring(0, 9);
			var r2 = strRegisterTime.Substring(9, 9);

			string result = u1 + r1 + u2 + r2;

			return DESEncrypt(result);
		}

		/// <summary>
		/// 把加密的信息进行解密，得到注册码的真实信息
		/// </summary>
		/// <param name="encryptedInfo"></param>
		/// <returns></returns>
		public static RegisterCodeInfo DecryptCode(string encryptedInfo)
		{
			if (string.IsNullOrWhiteSpace(encryptedInfo)) throw new ArgumentNullException("encryptedInfo");

			encryptedInfo = DESDecrypt(encryptedInfo);

			if (encryptedInfo.Length != 36) throw new InvalidOperationException("encryptedInfo.Length != 36 must be false.");

			var u1 = encryptedInfo.Substring(0, 9);
			var r1 = encryptedInfo.Substring(9, 9);
			var u2 = encryptedInfo.Substring(18, 9);
			var r2 = encryptedInfo.Substring(27, 9);

			var useTimeLimit = new DateTime(long.Parse(u1 + u2));
			var registerTimeLimit = new DateTime(long.Parse(r1 + r2));

			return new RegisterCodeInfo()
			{
				UseTimeLimit = useTimeLimit,
				RegisterTimeLimit = registerTimeLimit
			};
		}

		private static string DESEncrypt(string input)
		{
			return DES.Encrypt(input, PWD);
		}

		private static string DESDecrypt(string input)
		{
			return DES.Decrypt(input, PWD);
		}
	}

	/// <summary>
	/// 注册码信息
	/// </summary>
	public class RegisterCodeInfo
	{
		/// <summary>
		/// 能够使用的最后截止日期
		/// </summary>
		public DateTime UseTimeLimit { get; set; }

		/// <summary>
		/// 能够进行注册操作的最后截止日期
		/// </summary>
		public DateTime RegisterTimeLimit { get; set; }
	}
}
